﻿/*
 * jQuery Dynamic Breadcrumbs v1.0
 * http://code.google.com/p/jquery-dynamic-breadcrumbs/
 * http://twitter.com/blackdynamo
 * http://developingwithstyle.blogspot.com/
 *
 * Copyright 2010, Donnovan Lewis
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */

(function($){
    jQuery.fn.dynamicBreadcrumbs = function(options){
        //Capitalize extension for String
        String.prototype.capitalize = String.prototype.capitalize || function(){
            return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
        }; 
    
        //Defaults are below
        var settings = $.extend({}, $.fn.dynamicBreadcrumbs.defaults, options);
    
        return this.each(function(){
            setUpTrail($(this));
        });
        
        function setUpTrail(container){
			var path = settings.firstCrumbLabel + $(location).attr("pathname");

			var paths = path.split("/");
            var labels = cleanse(paths.slice(0));
            
            //Don't build any crumbs if the page is at the root
            if(labels.length <= 2) return;
            
            var crumbs = new Array();
            crumbs.push({name: labels[0], value: "/"}); //Initialize first crumb
            
            var list = $("<ul>");
            list.append(buildCrumb(crumbs[0]).addClass(settings.firstCrumbClass)); //Add first crumb
            
            //Build remaining crumbs
            for(var i = 1; i < labels.length-1; i++){
                crumbs.push({name: labels[i], value: crumbs[i-1].value + paths[i] + "/"});
                if(i == labels.length-2)
                    list.append(buildLastCrumb(crumbs[i]));
                else
                    list.append(buildCrumb(crumbs[i]));
            }
            
            container.append(list);
        }
        
		function cleanse(labels){
			for(var i = 0; i < labels.length; i++){
				//Remove all dashes
				labels[i] = labels[i].replace(/-/gi, " ");
				
				//Handle crumb case
				if(settings.crumbCase == "uppercase")
				    labels[i] = labels[i].toUpperCase();
				else if(settings.crumbCase == "lowercase")
				    labels[i] = labels[i].toLowerCase();
				else
				    labels[i] = labels[i].toLowerCase().capitalize();
				    
				//Replace keywords
				for(var w = 0; w < settings.keywords.length; w++){
				    labels[i] = labels[i].replace(eval("/"+settings.keywords[w]+"/gi"), settings.keywords[w])
			    }
			}
			
			return labels;
		}
		
        function buildCrumb(crumb){
            return $("<li>").append($("<a>").attr("href", crumb.value).append(crumb.name));
        }
        
        function buildLastCrumb(crumb){
            return $("<li>").append(crumb.name);
        }
    }
    
    jQuery.fn.dynamicBreadcrumbs.defaults = {
        firstCrumbLabel: "Home",
        firstCrumbClass: "first",
        crumbCase: "capitalize", //lowercase,uppercase,capitalize
        keywords: []
    }
})(jQuery);